package com.googlecode.jascii.printing;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;

import org.apache.commons.io.FileUtils;

import com.googlecode.jascii.TextReportReader;

public class TextPrintImage {
	private File txtFile;
	private File backImgFile = null;
	private float fontSize;
	private String encode = null;
	public TextPrintImage(File txtFile  , int fontSize , String encode) {
		super();
		this.txtFile = txtFile;
		this.fontSize = fontSize;
		this.encode = encode;
	}
	public TextPrintImage(File txtFile  , int fontSize  , String encode,File backImgFile) {
		super();
		this.txtFile = txtFile;
		this.fontSize = fontSize;
		this.encode = encode;
		this.backImgFile = backImgFile;
	}
	public String[] printPage(String imageName ) throws  IOException,TextNotFoundException
	{
		return printPage(imageName,-1,-1);
	}
	
	public String[] printPage(String imageName , int pageStart,int pageEnd) throws  IOException,TextNotFoundException
	{
		if(txtFile.exists())
		{
			String[] pages = null;
			TextReportReader reader = new TextReportReader(txtFile,encode);
			int lastpage = reader.getPages();
			
			if(pageStart<=0)
				pageStart=1;

			if(pageEnd > lastpage || pageEnd == -1)
				pageEnd = lastpage;
			else if(pageEnd < pageStart)
			{
				pageEnd = pageStart;
			}
			String[] returnStr = new String[pageEnd - pageStart+1];
			
//			String currpage= reader.getCurrentPage();
//			String[] pageLine = currpage.split("\n");
			
			int ireturnStr = 0;
			for(int i=pageStart;i<=pageEnd;i++)
			{
				String page = reader.getPage(i-1);
				
				BufferedImage bufferedImage = backImgFile==null? print(page):print(page,backImgFile);
				String fileName =  imageName+"_"+i+".png";
				returnStr[ireturnStr++] = fileName;
				ImageIO.write(bufferedImage, "png", new File( txtFile.getParentFile() ,fileName ));
			}
			
			return returnStr;
			
		}else
		{
			throw new TextNotFoundException("File not found:"+txtFile.getName());
		}
	}
	private BufferedImage print( String page , File backImgFile)
    {
			try {
				BufferedImage bufferedImage = ImageIO.read(backImgFile);
				Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics(); 
				this.print(page, g2);
				return bufferedImage;
			} catch (IOException e) {
				e.printStackTrace();
				return this.print(page);
			}
    }
	private BufferedImage print( String page)
    {
        String[] lineTxt = page.split("\n");
		
		int imageX = 0;
		int imageY = (int)((lineTxt.length ) * fontSize);
		String itempLine ="";
		for(String line : lineTxt)
		{
			int leng = line.length();
			if(leng>itempLine.length())
				itempLine = line;
		}
		imageX = itempLine.getBytes().length;
		imageX = (int)(imageX * fontSize /2) +2;
		
		
		BufferedImage bufferedImage = new BufferedImage( imageX,imageY, BufferedImage.TYPE_BYTE_BINARY);
		Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics(); 
		
		g2.clearRect(0,0,imageX,imageY);
		this.print(page, g2);
		return bufferedImage;
		
    }
	
	private void print( String page,Graphics2D g2)
    {
		String[] lineTxt = page.split("\n");
		g2.setBackground(Color.WHITE);
		g2.setPaint(Color.black); 
		Font fireflyFontDynamic = FontUtils.getFont("fireflysung.ttf");
		Font fireflyFont = fireflyFontDynamic.deriveFont(fontSize  );
		g2.setFont(fireflyFont); 
		int ix=1;
		float y = fontSize;
		for (int i = 0; i < lineTxt.length; i++) {
		      String line = (String)lineTxt[i];
		      for(int itemp=0;itemp<line.length();itemp++)
		      {
		    	  char ich = line.charAt(itemp);
		    	  String istr = String.valueOf(ich);
		    	  
		    	  if(istr.getBytes().length==1)
		    	  {
		    		  g2.drawString(String.valueOf(line.charAt(itemp)), (int)ix, (int)y);
		    	      ix+=fontSize/2;
		    	  }
		    	  else
		    	  {
		    		  g2.drawString(String.valueOf(line.charAt(itemp)), (int)ix, (int)y);
		    		  ix+=fontSize;
		    	  }
		    		  
		      }
		      y += fontSize;
		      ix=1;
		    }
		g2.dispose();
	}
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TextPrintImage print = new TextPrintImage(new File("Text.txt"),14,"BIG5",new File("back.jpg"));
		try {
			print.printPage("Test", 1, 3);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TextNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

//		RenderedImage rendImage = myCreateImage();
//    
//    // Write generated image to a file
//	    try {
//	        // Save as PNG
//	        File file = new File("newimage.png");
//	        ImageIO.write(rendImage, "png", file);
//	    
//	        // Save as JPEG
//	        file = new File("newimage.jpg");
//	        ImageIO.write(rendImage, "jpg", file);
//	    } catch (IOException e) {
//	    	e.printStackTrace();
//	    }
    }
    
    // Returns a generated image.
//    public static RenderedImage myCreateImage() {
//        int width = 100;
//        int height = 100;
//    
//        // Create a buffered image in which to draw
//        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//    
//        // Create a graphics contents on the buffered image
//        Graphics2D g2d = bufferedImage.createGraphics();
//    
//        // Draw graphics
//        g2d.setColor(Color.white);
//        g2d.fillRect(0, 0, width, height);
//        g2d.setColor(Color.black);
//        g2d.fillOval(0, 0, width, height);
//    
//        // Graphics context no longer needed so dispose it
//        g2d.dispose();
//    
//        return bufferedImage;
//    }

//	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
//			throws PrinterException {
//
//		Graphics2D g2 = (Graphics2D) graphics;
//		g2.setPaint(Color.black);
//		if (pageIndex > pageTxt.length)
//			return Printable.NO_SUCH_PAGE;
//		if (ipageStart > ipageEnd)
//			return Printable.NO_SUCH_PAGE;
//		System.out.println("pageIndex=" + ipageStart);
//		g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
//		// Font font = new Font("Serif", Font.PLAIN, fontSize);
//		Font fireflyFontDynamic = FontUtils.getFont("fireflysung.ttf");
//		Font fireflyFont = fireflyFontDynamic.deriveFont(fontSize);
//		// Font font = new Font("細明體", Font.PLAIN, fontSize);//設置字型
//
//		g2.setFont(fireflyFont);
//
//		String page = pageTxt[ipageStart++];
//		String[] lineTxt = page.split("\n");
//
//		int ix = 0;
//		float y = fontSize;
//		for (int i = 0; i < lineTxt.length; i++) {
//			String line = (String) lineTxt[i];
//			for (int itemp = 0; itemp < line.length(); itemp++) {
//				char ich = line.charAt(itemp);
//				String istr = String.valueOf(ich);
//
//				if (istr.getBytes().length == 1) {
//					g2.drawString(String.valueOf(line.charAt(itemp)), (int) ix,
//							(int) y);
//					ix += fontSize / 2;
//				} else {
//					g2.drawString(String.valueOf(line.charAt(itemp)), (int) ix,
//							(int) y);
//					ix += fontSize;
//				}
//
//			}
//			y += fontSize;
//			ix = 0;
//		}
//
//		return Printable.PAGE_EXISTS;
//	}

}
